import re

from rest_framework import serializers


# 因为是根据模型自动生成字段　
from rest_framework_jwt.settings import api_settings

from areas.models import Area
from users.models import User, Address


class RegisterAPIViewSerializer(serializers.ModelSerializer):

    allow = serializers.CharField(label='是否同意协议',allow_blank=False,allow_null=False,write_only=True)
    password2 = serializers.CharField(label='密码',max_length=20,min_length=8,allow_null=False,allow_blank=False,write_only=True)
    sms_code = serializers.CharField(label='短信验证',max_length=6,min_length=6,write_only=True,allow_blank=False,allow_null=False)
    token = serializers.CharField(label='token',read_only=True)

    class Meta:
        model = User
        fields = ['allow','password2','sms_code','id','username','password','mobile','token']

        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 实现单个字段的校验
    def validated_mobile(self,value):

        if not re.match(r'1[3-9]\d{9}',value):
            raise serializers.ValidationError('手机号格式不对')

        return value

    def validated_allow(self,value):

        if value != 'True':
            raise serializers.ValidationError('您未同意协议')

        return value

    # 多个字段的校验
    def validate(self, attrs):

        password2 = attrs.get('password2')
        password = attrs.get('password')

        if password != password2:
            raise serializers.ValidationError('两次输入的密码不一致')

        sms_code = attrs.get('sms_code')

        from django_redis import get_redis_connection

        redis_conn = get_redis_connection('code')

        redis_sms = redis_conn.get('sms_%s'%attrs.get('mobile'))

        if redis_sms is None:
            raise serializers.ValidationError('短信验证码已经过期')

        if redis_sms.decode()!=sms_code:
            raise serializers.ValidationError('短信验证码输入有误')

        return attrs

    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = User.objects.create(**validated_data)
        # 因为密码是明文　所以需要用django 认证去加密
        user.set_password(validated_data['password'])

        user.save()
        # 注册完成的时候需要将token返回　在序列化器中　创建token 的值　
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        user.token = token

        return user


class UserInfoAPIViewSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','email','email_active','mobile']


class EmailSendAPIVIewSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','email']
        extra_kwargs = {
            'email':{'required':True}
        }


class AddAdressAPIViewSerializer(serializers.ModelSerializer):
    # 序列化的时候使用
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    # 反序列化的时候使用
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Area
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    def create(self, validated_data):

        user = self.context.get('request').user
        validated_data['user'] = user

        user = Area.objects.create(**validated_data)
        user.save()
        return user


class AddAddressSerializer(serializers.ModelSerializer):
    # 序列化使用
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    # 反序列化使用
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    # 对手机号进一步的验证
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        fields = ['title','receiver','province','city','district','place','mobile','tel','email','province_id','city_id','district_id']

    def create(self, validated_data):
        # 取到user
        user = self.context.get('request').user
        # 将user 对象加到数据中
        validated_data['user'] = user
        add = Address.objects.create(**validated_data)
        add.save()

        return add


# class GETAddressSerializer(serializers.ModelSerializer):
#
#     class Meta:
#         fields = ['title','receiver','place','mobile','tel','email','province_id','city_id','district_id']

